﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Configuration;
using System.DirectoryServices.Protocols;
using System.Net;
using System.Globalization;
using Wicresoft.UnifyShow.BusinessImpl;
using Wicresoft.UnifyShow.Business;
using System.Text;

namespace Wicresoft.UnifyShow2.Portal.Controllers
{
    public class AccountController : Controller
    {

        //
        // GET: /Account/LogOff

        private static string cookieUnifyKey = ConfigurationManager.AppSettings["SSOCookie"];
        private static string isDecrypt = ConfigurationManager.AppSettings["isDecrypt"];

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            HttpCookie myCookie = Request.Cookies["fj-itsm-sso"];
            if (myCookie != null)
            {
                myCookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(myCookie);
            }
            return RedirectToAction("LogOn", "Account");
        }


        private bool Authentication(string username, string password, string server)
        {
            bool ret = true;
            if (ConfigurationManager.AppSettings["AuthMethod"] == "Debug")
                return ret;
            //use web service auth
            if (ConfigurationManager.AppSettings["AuthMethod"] == "Service")
            {
                try
                {
                    TSMSyncSoapClient client = new TSMSyncSoapClient();
                    ret = client.Authentication(username, password);
                }
                catch (Exception e)
                {
                    ret = false;
                }
            }
            else
            {

                string dn = null;
                LdapConnection ldap = null;
                try
                {
                    ldap = new LdapConnection(new LdapDirectoryIdentifier(server),
                        null, AuthType.Anonymous);
                    ldap.SessionOptions.ProtocolVersion = 3;
                    dn = GetDn(ldap, username);
                    if (dn == null)
                        ret = false;

                }
                catch
                {
                    ret = false;
                }
                finally
                {
                    if (ldap != null)
                        ldap.Dispose();
                }

                if (ret == false) return false;

                try
                {
                    ldap = new LdapConnection(new LdapDirectoryIdentifier(server),
                        new NetworkCredential(dn, password), AuthType.Basic);
                    ldap.SessionOptions.ProtocolVersion = 3;
                    ldap.Bind();
                }
                catch
                {
                    ret = false;
                }
                finally
                {
                    if (ldap != null)
                        ldap.Dispose();
                }
            }

            return ret;

        }

        private String GetDn(LdapConnection ldap, String userName)
        {
            var request = new SearchRequest("o=福建烟草", string.Format(CultureInfo.InvariantCulture, "cn={0}", userName), SearchScope.Subtree);
            var response = (SearchResponse)ldap.SendRequest(request);
            if (response.Entries.Count == 1)
            {
                return response.Entries[0].DistinguishedName;
            }
            return null;
        }

        //
        // GET: /Account/

        public ActionResult LogOn()
        {
            ViewData["Error"] = false;
            return View(new LogOnRequestModel());
        }

        public ActionResult LogOnSSO()
        {
            using (User_X user_x = new User_X())
            {
                User_XModel user = AuthenticationSSOCookie(user_x, Request);
                if (user != null)
                {
                    var sites = user_x.GetSiteBranchByID(user.ID);
                    if (sites.Count > 0 && sites.FirstOrDefault(s => s.Name == user.Company) != null)
                    {
                        FormsAuthentication.SetAuthCookie(user.Name, false);

                        //省局信息中心的人 首页进去 今日运维一览
                        if (string.Equals(user.Company.Trim(), "福建省烟草专卖局") && string.Equals(user.Department.Trim(), "经济信息中心"))
                        {
                            return RedirectToAction("Maintenance", "Navigate");
                        }

                        return RedirectToAction("Index", "Navigate");

                    }
                    else
                    {
                        return Redirect("/Error/SSOPermissionError.html");
                    }
                }
                else
                {
                    return Redirect("/Error/SSOPermissionError.html");
                }
            }
            return View(new LogOnRequestModel());
        }

        public static Dictionary<string, string> DecryptCookie(string value)
        {
            Dictionary<string, string> values = new Dictionary<string, string>();
            string valueD = Decrypt(value);
            string[] namevalue = null;

            foreach (var item in valueD.Split('&'))
            {
                namevalue = item.Split('=');
                if (namevalue.Length == 2)
                    values.Add(namevalue[0], namevalue[1]);
            }

            return values;

        }

        //TODO Decrypt
        public static string Decrypt(string value)
        {
            string result = string.Empty;

            if (string.IsNullOrWhiteSpace(isDecrypt))
            {
                using (WebClient client = new WebClient())
                {
                    client.Encoding = Encoding.UTF8;
                    result = client.DownloadString("http://10.188.238.29:9898/DS/Do?DD=" + HttpUtility.UrlEncodeUnicode(value)).Trim();
                    //result = client.DownloadString("http://localhost:8080/DS/Do?DD=" + HttpUtility.UrlEncodeUnicode(value)).Trim();
                }
            }
            else
            {
                result = value;
            }

            //return "cn=姓名&uid=用户编号&dept=部门&apps=应用编号&logintime=登录时间";
            return result;
        }

        public static User_XModel AuthenticationSSOCookie(IUser_X user, HttpRequestBase request1)
        {

            try
            {
                //not set SSOCookie config,don't try SSO Authentication
                if (string.IsNullOrEmpty(cookieUnifyKey)) return null;

                //try get cookie
                var cookie = request1.Cookies[cookieUnifyKey];

                //SSO cookie exsit
                if (cookie != null)
                {
                    Dictionary<string, string> values = DecryptCookie(cookie.Value);
                    //Dictionary<string, string> values = DecryptCookie("1s2SL2IP8oIGzIhf3OE+yu11iZcJVLRqYI+22Dh8wA5gNJLoG3HQOPAPta/BQbpW3b27X5bvCSQmU81zyxB0zPqUgOtGZFc3N04xqLCxpiGpJ5HKiikpE5231YZqjZsHHA==");

                    DateTime date = DateTime.Now.AddHours(-18);
                    bool isApp = false;
                    User_XModel userM = null;
                    if (!string.IsNullOrWhiteSpace(values["uid"]))
                    {
                        userM = user.GetUserByPeopleNo(values["uid"]);
                    }


                    string tmp = string.Empty;
                    foreach (var item in values["apps"].Split(','))
                    {
                        tmp = item.Trim();
                        if (tmp == "600000")
                            isApp = true;
                    }

                    if (DateTime.TryParse(values["logintime"], out date))
                    {
                        if ((userM != null) && (!string.IsNullOrWhiteSpace(userM.Name)) && date.AddHours(4) > DateTime.Now && isApp)
                        {
                            return userM;
                        }
                    }


                }
            }
            catch (Exception e)
            {
                return null;
            }

            return null;
        }

        [HttpPost]
        public ActionResult LogOn(LogOnRequestModel model, string returnUrl)
        {

            //CustomLoginUtil.Login(request.UserName, true);
            if (ModelState.IsValid)
            {
                //if (model.Pwd == "User@123" || Authentication(model.UserName, model.Pwd, "10.188.238.27"))  //model.Pwd == "User@123" || 
                if (Authentication(model.UserName, model.Pwd, "10.188.238.27"))
                {

                    using (User_X user_x = new User_X())
                    {
                        User_XModel user = user_x.GetUser_XByName(model.UserName.ToLower());
                        if (user != null)
                        {
                            var sites = user_x.GetSiteBranchByID(user.ID);
                            if (sites.Count > 0 && sites.FirstOrDefault(s => s.Name == user.Company) != null)
                            {
                                FormsAuthentication.SetAuthCookie(model.UserName, false);
                                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                                {
                                    return Redirect(returnUrl);
                                }
                                else
                                {
                                    //省局信息中心的人 首页进去 今日运维一览
                                    if (string.Equals(user.Company.Trim(), "福建省烟草专卖局") && string.Equals(user.Department.Trim(), "经济信息中心"))
                                    {
                                        return RedirectToAction("Maintenance", "Navigate");
                                    }
                                    return RedirectToAction("Index", "Navigate");
                                }
                            }
                            else
                            {
                                return Redirect("/Error/PermissionError.html");
                            }
                        }
                        else
                        {
                            ViewData["Error"] = true;
                        }
                    }

                }
                else
                {
                    ViewData["Error"] = true;
                }
            }
            else
            {
                ViewData["Error"] = false;
            }
            // If we got this far, something failed, redisplay form
            return View(model);

        }

        //[HttpPost]
        //public ActionResult LogOn(LogOnRequestModel model, string returnUrl)
        //{

        //    //CustomLoginUtil.Login(request.UserName, true);
        //    if (ModelState.IsValid)
        //    {
        //        //if (model.Pwd == "User@123" || Authentication(model.UserName, model.Pwd, "10.188.238.27"))  //model.Pwd == "User@123" || 
        //        if (Authentication(model.UserName, model.Pwd, "10.188.238.27"))
        //        {

        //            using (User_X user_x = new User_X())
        //            {
        //                User_XModel user = user_x.GetUser_XByName(model.UserName.ToLower());
        //                if (user != null)
        //                {
        //                    var sites = user_x.GetSiteBranchByID(user.ID);
        //                    if (sites.Count > 0 && sites.FirstOrDefault(s => s.Name == user.Company) != null)
        //                    {
        //                        FormsAuthentication.SetAuthCookie(model.UserName, false);
        //                        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
        //                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
        //                        {
        //                            return Redirect(returnUrl);
        //                        }
        //                        else
        //                        {
        //                            //省局信息中心的人 首页进去 今日运维一览
        //                            if (string.Equals(user.Company.Trim(), "福建省烟草专卖局") && string.Equals(user.Department.Trim(), "经济信息中心"))
        //                            {
        //                                return RedirectToAction("Maintenance", "Navigate");
        //                            }
        //                            return RedirectToAction("Index", "Navigate");
        //                        }
        //                    }
        //                    else
        //                    {
        //                        return Redirect("/Error/PermissionError.html");
        //                    }
        //                }
        //                else
        //                {
        //                    ViewData["Error"] = true;
        //                }
        //            }

        //        }
        //        else
        //        {
        //            ViewData["Error"] = true;
        //        }
        //    }
        //    else
        //    {
        //        ViewData["Error"] = false;
        //    }
        //    // If we got this far, something failed, redisplay form
        //    return View(model);

        //}


        public ActionResult HeaderContent()
        {
            return PartialView();
        }


        //[HttpPost]
        public ActionResult SSO(string redirectionUrl)
        {
            var context = this.HttpContext;
            if (context != null)
            {
                HttpCookie httpcookie = new HttpCookie("fj-itsm-sso", selfEncrypt(User.Identity.Name + "|User@123", 3));

#if DEBUG
                string orignalDomain = "selfservice.fj-tobacco.com";
#else
                string orignalDomain = context.Request.ServerVariables["SERVER_NAME"].ToString();
#endif

                if (orignalDomain.Contains('.'))
                {
                    int begin = orignalDomain.IndexOf('.');
                    httpcookie.Domain = orignalDomain.Substring(begin);
                    httpcookie.Path = "/";
                }
                //httpcookie.Domain = context.Request.ServerVariables["SERVER_NAME"].ToString();
                context.Response.Cookies.Add(httpcookie);
            }
            else
            {
                return RedirectToAction("SSOFailed");
            }
            return Redirect(Server.UrlDecode(redirectionUrl));

        }

        public ActionResult SSOFailed()
        {
            return View();
        }

        private string selfEncrypt(string input, int key)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            string HexStr = string.Empty;

            List<int> orgint = new List<int>();

            for (int i = 0; i < input.Length; i++)
            {
                int asc_char = Convert.ToInt32(input[i]);
                orgint.Add(asc_char - 3);
            }

            for (int j = 0; j < orgint.Count() - 1; j++)
            {
                orgint[j + 1] = orgint[j] ^ orgint[j + 1];
            }

            for (int k = 0; k < orgint.Count(); k++)
            {
                HexStr += orgint[k].ToString("X02");
            }


            return HexStr;
        }

    }
}
